package com.zhj.juc.demo7;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @PackageName:com.zhj.juc.demo7
 * @ClassName:Test1ReadWriteLock
 * @auter: 朱慧杰
 * @date:2020/7/24 0024 8:18
 **/
public class Test1ReadWriteLock {

    /**
     * 独占锁  写锁  一个线程占有
     * 共享锁  读锁  多个线程占有
     * ReadWriteLock
     * 读读，可以共存
     * 读写，不能共存
     * 写写，不能共存
     * @param args
     */

    public static void main(String[] args) {
        // MyCache myCache = new MyCache();
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 0; i < 30; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.put(temp + "", temp + "");
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 30; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.get(temp + "");
            },String.valueOf(i)).start();
        }

    }

}

/**
 * 自定义缓存
 */
class MyCache {

    private volatile Map<String,Object> map = new HashMap<>();

    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "写入: " + key);
        map.put(key,value);
        System.out.println("写入成功！");
    }

    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取: " + key);
        Object o = map.get(key);
        System.out.println("读取成功！");
    }

}

// 加锁的
class MyCacheLock {

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private volatile Map<String,Object> map = new HashMap<>();

    public void put(String key, Object value) {

        readWriteLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "写入: " + key);
            map.put(key,value);
            System.out.println("写入成功！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取: " + key);
            Object o = map.get(key);
            System.out.println("读取成功！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

}